package com.ogawa.project6602.activity

import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.ogawa.base.bean.LoadState
import com.ogawa.base.constants.Constants
import com.ogawa.base.utils.ToastUtil
import com.ogawa.project6602.fragment.DIY6602Fragment
import com.ogawa.project6602.R
import com.ogawa.project6602.adapter.DIY6602Adapter
import com.ogawa.project6602.base.Base6602MqttActivity
import com.ogawa.project6602.bean.Massage6602Armchair
import com.ogawa.project6602.dialog.DiyNameDialog
import com.ogawa.project6602.viewmodel.DiyViewModel
import com.ogawa.projectcommon.bean.*
import com.ogawa.projectcommon.constants.Constant
import com.ogawa.projectcommon.constants.UrlPathConstant
import com.ogawa.projectcommon.dialog.DiyShareDialog
import com.ogawa.projectcommon.utils.ProjectSpUtils
import com.ogawa.projectcommon.widget.*
import kotlinx.android.synthetic.main.activity_d_i_y_6602.*

@Route(path = UrlPathConstant.ACTIVITY_6602_ManualMode)
class Device6602DIYActivity : Base6602MqttActivity(), View.OnClickListener {
    private lateinit var viewPageAdapter: DIY6602Adapter
    private var jxEditDialog: JxEditDialog? = null
    private var gasEditDialog: GasEditDialog? = null
    private var heatEditDialog: HeatEditDialog? = null
    private var rollEditDialog: RollEditDialog? = null
    private var diyNameDialog: DiyNameDialog? = null
    private var diyShareDialog: DiyShareDialog? = null
    private lateinit var diyFragment1: DIY6602Fragment
    private lateinit var diyFragment2: DIY6602Fragment
    private lateinit var diyFragment3: DIY6602Fragment
    private lateinit var diyViewModel: DiyViewModel
    private lateinit var currentFragment: DIY6602Fragment
    private var currentTextView: TextView? = null
    private var currentDiyIndex = 0
    private var isSync = false

    override fun getLayoutId(): Int {
        return R.layout.activity_d_i_y_6602
    }

    override fun initView() {
        super.initView()
        setTitle(getString(R.string.diy_title))
        setAddVis(true)
        setMsgVis(true)
        setRightImg(R.drawable.img_share)
        setSecondRightImg(R.drawable.img_explain)
        setMsgOnclick(View.OnClickListener {
            //说明
            ARouter.getInstance().build(UrlPathConstant.ACTIVITY_WEB_VIEW)
                .withString("titleStr", getString(R.string.control_introduction))
                .withString("url", Constant.DIY_INTRODUCTION_URL)
                .navigation()
        })
        setAddOnclick(View.OnClickListener {
            //分享到官方
            showDiyShareDialog()
        })
        initViewPager()
        changePage(0)
        diy1Tv.setOnClickListener(this)
        diy2Tv.setOnClickListener(this)
        diy3Tv.setOnClickListener(this)
        iv_diy1_delete.setOnClickListener(this)
        iv_diy2_delete.setOnClickListener(this)
        iv_diy3_delete.setOnClickListener(this)
        diy1Tv.setOnLongClickListener {
            if (currentFragment == diyFragment1 /*&& currentDiyIndex != 1*/) {
                iv_diy1_delete.visibility = View.VISIBLE
            }
            return@setOnLongClickListener true
        }
        diy2Tv.setOnLongClickListener {
            if (currentFragment == diyFragment2 /*&& currentDiyIndex != 2*/) {
                iv_diy2_delete.visibility = View.VISIBLE
            }
            return@setOnLongClickListener true
        }
        diy3Tv.setOnLongClickListener {
            if (currentFragment == diyFragment3 /*&& currentDiyIndex != 3*/) {
                iv_diy3_delete.visibility = View.VISIBLE
            }
            return@setOnLongClickListener true
        }
        ll_root.setOnClickListener(this)
        movementLL.setOnClickListener(this)
        gasbagLL.setOnClickListener(this)
        heatingLL.setOnClickListener(this)
        foot_rollLL.setOnClickListener(this)
        tv_save_program.setOnClickListener(this)
        tv_test_program.setOnClickListener(this)
        diyViewModel = ViewModelProviders.of(this).get(DiyViewModel::class.java)
        diyViewModel.loadState.observe(this, Observer {
            when (it) {
                is LoadState.Loading -> {
                    showLoadingDialog(canceledOnTouchOutside = false)
                }
                is LoadState.Fail -> {
                    dismissLoadingDialog()
                    ToastUtils.showShort(it.msg)
                }
                is LoadState.Success -> {
                    if (it.msg == "1") {
                        ToastUtil.showToast(getString(R.string.share_success), Toast.LENGTH_SHORT)
                    }
                    dismissLoadingDialog()
                }
            }
        })
        diyViewModel.diyPrograms.observe(this, Observer {
            for (i in it.indices) {
                setDiyInfo(it[i])
            }
        })
        diyViewModel.diyBeanData.observe(this, Observer {
            ToastUtil.showToast(getString(R.string.save_success), Toast.LENGTH_SHORT)
            setDiyInfo(it)
        })
        diyViewModel.getDiyProgram()
    }

    private fun initViewPager() {
        viewPageAdapter =
            DIY6602Adapter(supportFragmentManager)
        diyFragment1 = DIY6602Fragment("1", "")
        diyFragment2 = DIY6602Fragment("2", "")
        diyFragment3 = DIY6602Fragment("3", "")
        viewPageAdapter.addFragment(diyFragment1)
        viewPageAdapter.addFragment(diyFragment2)
        viewPageAdapter.addFragment(diyFragment3)
        currentFragment = diyFragment1
        viewPage.adapter = viewPageAdapter
        viewPage.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                onDeviceStateChange()
                changePage(position)
            }
        })
    }

    private fun changePage(position: Int) {
        dismissDelete()
        when (position) {
            0 -> {
                currentTextView = diy1Tv
                currentFragment = diyFragment1
            }
            1 -> {
                currentTextView = diy2Tv
                currentFragment = diyFragment2

            }
            2 -> {
                currentTextView = diy3Tv
                currentFragment = diyFragment3

            }
        }
        diy1Tv.setBackgroundResource(
            if (position == 0) {
                R.drawable.shape_bg_3fc5fd_radius_all_5
            } else {
                R.drawable.shape_bg_gray9f_radius_all_5
            }
        )
        diy2Tv.setBackgroundResource(
            if (position == 1) {
                R.drawable.shape_bg_3fc5fd_radius_all_5
            } else {
                R.drawable.shape_bg_gray9f_radius_all_5
            }
        )
        diy3Tv.setBackgroundResource(
            if (position == 2) {
                R.drawable.shape_bg_3fc5fd_radius_all_5
            } else {
                R.drawable.shape_bg_gray9f_radius_all_5
            }
        )
    }

    private fun dismissDelete() {
        iv_diy1_delete.visibility = View.GONE
        iv_diy2_delete.visibility = View.GONE
        iv_diy3_delete.visibility = View.GONE
    }

    private fun setDiyInfo(diyBean: DiyBean) {
        when (diyBean.appIndex) {
            1 -> {
                diy1Tv.text = diyBean.diyName
                diyFragment1.setDiyContent(diyBean)
            }
            2 -> {
                diy2Tv.text = diyBean.diyName
                diyFragment2.setDiyContent(diyBean)
            }
            3 -> {
                diy3Tv.text = diyBean.diyName
                diyFragment3.setDiyContent(diyBean)
            }
        }
    }

    override fun onClick(p0: View?) {
        dismissDelete()
        when (p0?.id) {
            R.id.diy1Tv -> viewPage.setCurrentItem(0, true)
            R.id.diy2Tv -> viewPage.setCurrentItem(1, true)
            R.id.diy3Tv -> viewPage.setCurrentItem(2, true)
            R.id.movementLL -> {
                showJxEditDialog()
            }
            R.id.gasbagLL -> {
                showGasEditDialog()
            }
            R.id.heatingLL -> {
                showHeatEditDialog()
            }
            R.id.foot_rollLL -> {
                showRollEditDialog()
            }
            R.id.tv_save_program -> {
                var currentProgramName = ""
                if (currentTextView != null) {
                    currentProgramName = currentTextView!!.text.toString()
                }
                showDiyNameDialog(currentProgramName)
            }
            R.id.tv_test_program -> {
                publish(Constants.DIY_PROGRAM, currentFragment.getDiyCommand())
            }
            R.id.iv_diy1_delete, R.id.iv_diy2_delete, R.id.iv_diy3_delete -> {
                currentFragment.clearDiyData()
            }
        }
    }

    fun showJxEditDialog(movementBean: MovementBean? = null) {
        if (jxEditDialog == null) {
            jxEditDialog = JxEditDialog(this)
        }
        var excludeRange: TimeRange? = null
        if (movementBean != null) {
            excludeRange = TimeRange(movementBean.startTime, movementBean.endTime)
        }
        jxEditDialog?.setConfirmClickListener(View.OnClickListener {
            val startTime = jxEditDialog!!.getStartTime()
            val endTime = jxEditDialog!!.getEndTime()
            val sideType = jxEditDialog!!.getSideType()
            val handType = jxEditDialog!!.getHandType()
            val width = jxEditDialog!!.getWidth()
            val strength = jxEditDialog!!.getStrongRank()
            val speed = jxEditDialog!!.getSpeedRank()
            val lev5D = jxEditDialog!!.get5DRank()
            if (!jxEditDialog!!.isTimeLegal()) {
                ToastUtil.showToast(getString(R.string.time_illegal), Toast.LENGTH_SHORT)
            } else if (sideType == -1 ||handType==-1/*|| width == 0 || strength == 0 || speed == 0*/) {//信息未完善
                ToastUtil.showToast(getString(R.string.massage_info_tip), Toast.LENGTH_SHORT)
            } else {
                if (movementBean == null) {
                    val movement =
                        MovementBean(
                            startTime,
                            endTime,
                            sideType,
                            handType,
                            width,
                            strength,
                            speed,
                            lev5D
                        )
                    currentFragment.addMovement(movement)
                } else {
                    movementBean.startTime = startTime
                    movementBean.endTime = endTime
                    movementBean.sideType = sideType
                    movementBean.handType = handType
                    movementBean.widthRank = width
                    movementBean.strongRank = strength
                    movementBean.speedRank = speed
                    movementBean.gearDRank = lev5D
                    currentFragment.refreshView()
                }
                jxEditDialog!!.dismiss()
            }
        })
        currentFragment.setTimeRange(0, jxEditDialog!!.getTimeRangeView(), excludeRange)
        jxEditDialog!!.show(movementBean)
    }

    fun showGasEditDialog(gasBean: GasBean? = null) {
        if (gasEditDialog == null) {
            gasEditDialog = GasEditDialog(this)
        }
        var excludeRange: TimeRange? = null
        if (gasBean != null) {
            excludeRange = TimeRange(gasBean.startTime, gasBean.endTime)
        }
        gasEditDialog!!.setConfirmClickListener(View.OnClickListener {
            val shoulderLev = gasEditDialog!!.getShoulderLev()
            val armLev = gasEditDialog!!.getArmLev()
            val legLev = gasEditDialog!!.getLegLev()
            val seatLev = gasEditDialog!!.getSeatLev()
            if (!gasEditDialog!!.isTimeLegal()) {
                ToastUtil.showToast(getString(R.string.time_illegal), Toast.LENGTH_SHORT)
            } else if (shoulderLev == 0 && armLev == 0 && legLev == 0 && seatLev == 0) {
                ToastUtil.showToast(getString(R.string.massage_info_tip), Toast.LENGTH_SHORT)
            } else {
                if (gasBean == null) {
                    val gas = GasBean(
                        gasEditDialog!!.getStartTime(),
                        gasEditDialog!!.getEndTime(),
                        shoulderLev,
                        armLev,
                        legLev,
                        seatLev
                    )
                    currentFragment.addGas(gas)
                } else {
                    gasBean.startTime = gasEditDialog!!.getStartTime()
                    gasBean.endTime = gasEditDialog!!.getEndTime()
                    gasBean.shoulderRank = shoulderLev
                    gasBean.handRank = armLev
                    gasBean.legRank = legLev
                    gasBean.seatRank = seatLev
                    currentFragment.refreshView()
                }
                gasEditDialog!!.dismiss()
            }
        })
        currentFragment.setTimeRange(1, gasEditDialog!!.getTimeRangeView(), excludeRange)
        gasEditDialog?.show(gasBean)
    }

    fun showHeatEditDialog(heatBean: HeatRollBean? = null) {
        if (heatEditDialog == null) {
            heatEditDialog = HeatEditDialog(this)
        }
        var excludeRange: TimeRange? = null
        if (heatBean != null) {
            excludeRange = TimeRange(heatBean.startTime, heatBean.endTime)
        }
        heatEditDialog!!.setConfirmClickListener(View.OnClickListener {
            if (!heatEditDialog!!.isTimeLegal()) {
                ToastUtil.showToast(getString(R.string.time_illegal), Toast.LENGTH_SHORT)
            } else {
                if (heatBean == null) {
                    val heat =
                        HeatRollBean(
                            heatEditDialog!!.getStartTime(),
                            heatEditDialog!!.getEndTime()
                        )
                    currentFragment.addHeat(heat)
                } else {
                    heatBean.startTime = heatEditDialog!!.getStartTime()
                    heatBean.endTime = heatEditDialog!!.getEndTime()
                    currentFragment.refreshView()
                }
                heatEditDialog!!.dismiss()
            }
        })
        currentFragment.setTimeRange(2, heatEditDialog!!.getTimeRangeView(), excludeRange)
        heatEditDialog?.show(heatBean)
    }

    fun showRollEditDialog(rollBean: HeatRollBean? = null) {
        if (rollEditDialog == null) {
            rollEditDialog = RollEditDialog(this)
        }
        var excludeRange: TimeRange? = null
        if (rollBean != null) {
            excludeRange = TimeRange(rollBean.startTime, rollBean.endTime)
        }
        rollEditDialog!!.setConfirmClickListener(View.OnClickListener {
            if (!rollEditDialog!!.isTimeLegal()) {
                ToastUtil.showToast(getString(R.string.time_illegal), Toast.LENGTH_SHORT)
            } else {
                if (rollBean == null) {
                    val roll =
                        HeatRollBean(rollEditDialog!!.getStartTime(), rollEditDialog!!.getEndTime())
                    currentFragment.addRoll(roll)
                } else {
                    rollBean.startTime = rollEditDialog!!.getStartTime()
                    rollBean.endTime = rollEditDialog!!.getEndTime()
                    currentFragment.refreshView()
                }
                rollEditDialog!!.dismiss()
            }
        })
        currentFragment.setTimeRange(3, rollEditDialog!!.getTimeRangeView(), excludeRange)
        rollEditDialog?.show(rollBean)
    }

    private fun showDiyNameDialog(diyName: String? = null) {
        if (diyNameDialog == null) {
            diyNameDialog = DiyNameDialog(this)
            diyNameDialog!!.setOnSaveClickListener(View.OnClickListener {
                val inputContent = diyNameDialog!!.getInputContent()
                if (!inputContent.isBlank()) {
                    val diyBean = currentFragment.getDiyBean()
                    if (diyBean != null) {
                        diyBean.diyName = inputContent
                        diyViewModel.saveDiyProgram(diyBean)
                    } else {
                        ToastUtil.showToast(
                            getString(R.string.no_program_info_tip),
                            Toast.LENGTH_SHORT
                        )
                    }
                    diyNameDialog!!.dismiss()
                }
            })
        }
        diyNameDialog?.show(diyName)
    }

    private fun showDiyShareDialog() {
        if (diyShareDialog == null) {
            diyShareDialog = DiyShareDialog(this)
            diyShareDialog!!.setOnConfirmClickListener(View.OnClickListener {
                val diyBean = currentFragment.getDiyBean(true)
                val id = diyBean?.id
//                val content = diyBean?.content
//                var diyContentBean: DiyContentBean? = null
//                if (content != null) {
//                    diyContentBean =
//                        Gson().fromJson<DiyContentBean>(content, DiyContentBean::class.java)
//                }
                val userInfo = ProjectSpUtils.getUserInfo()
                if (userInfo.isVisitor) {
                    ToastUtil.showToast(
                        getString(R.string.diy_share_tip),
                        Toast.LENGTH_SHORT
                    )
                    diyShareDialog!!.dismiss()
                    return@OnClickListener
                }
                if (id == null /*|| diyContentBean == null || diyContentBean.isEmpty()*/) {
                    ToastUtil.showToast(getString(R.string.diy_share_info_tip), Toast.LENGTH_SHORT)
                } else {
                    diyViewModel.shareDiy(id.toString())
                }
                diyShareDialog!!.dismiss()
            })
        }
        diyShareDialog?.show()
    }

    override fun onDeviceStateChange() {
        super.onDeviceStateChange()
        val deviceStatusBean = Massage6602Armchair.getInstance().deviceStatusBean
        if (deviceStatusBean != null) {
            val diyProgramKey = deviceStatusBean.functions.diyProgramKey
            val diyProgramKeyValue = diyProgramKey.modelValue.toInt()
            if (!isSync) {
                viewPage.let {
                    it.setCurrentItem(diyProgramKeyValue - 1, false)
                    isSync = true
                }
            }
            if (currentDiyIndex != diyProgramKeyValue) {
                dismissDelete()
                currentDiyIndex = diyProgramKeyValue
            }
            diyFragment1.onDeviceStateChange()
            diyFragment2.onDeviceStateChange()
            diyFragment3.onDeviceStateChange()
//            currentFragment.setWidgetTouchEnable(currentDiyIndex != viewPage.currentItem + 1)
//            iv_movement.isEnabled = currentDiyIndex != viewPage.currentItem + 1
//            iv_gas.isEnabled = currentDiyIndex != viewPage.currentItem + 1
//            iv_heat_adjust.isEnabled = currentDiyIndex != viewPage.currentItem + 1
//            iv_roll.isEnabled = currentDiyIndex != viewPage.currentItem + 1
//            movementLL.isEnabled = currentDiyIndex != viewPage.currentItem + 1
//            gasbagLL.isEnabled = currentDiyIndex != viewPage.currentItem + 1
//            heatingLL.isEnabled = currentDiyIndex != viewPage.currentItem + 1
//            foot_rollLL.isEnabled = currentDiyIndex != viewPage.currentItem + 1
        }
    }
}